package controller

import (
	"admin/model"
	"common/helper"
	"encoding/json"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"net/url"
	"strings"
)

type GameController struct{}

// 游戏列表

func (that *GameController) Search(ctx *fasthttp.RequestCtx) {
	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	word := string(ctx.QueryArgs().Peek("word"))
	platformId := ctx.QueryArgs().GetUintOrZero("platform_id")
	gameType := ctx.QueryArgs().GetUintOrZero("game_type")
	online := ctx.QueryArgs().GetUintOrZero("online")
	gameId := string(ctx.QueryArgs().Peek("game_id"))
	isHot := ctx.QueryArgs().GetUintOrZero("is_hot") //热门
	isNew := ctx.QueryArgs().GetUintOrZero("is_new") //推荐 1 开启  2 关闭
	isFav := ctx.QueryArgs().GetUintOrZero("is_fav") //最新
	orderBy := string(ctx.QueryArgs().Peek("order_by"))
	OderType := string(ctx.QueryArgs().Peek("order_type"))

	if page < 1 {
		page = 1
	}
	if pageSize < 10 || pageSize > 100 {
		pageSize = 10
	}

	filter := ""
	if platformId > 0 {
		filter = fmt.Sprintf(" pid = %d", platformId)
	}
	if gameType > 0 {
		if len(filter) == 0 {
			filter = fmt.Sprintf("game_type = %d", gameType)
		} else {
			filter += fmt.Sprintf(" AND game_type = %d", gameType)
		}
	}
	if isNew == 1 {
		if len(filter) == 0 {
			filter += fmt.Sprintf(" is_new = %d", isNew)
		} else {
			filter += fmt.Sprintf(" AND is_new = %d", isNew)
		}
	}

	if isHot == 1 {
		if len(filter) == 0 {
			filter += fmt.Sprintf(" is_hot = %d", isNew)
		} else {
			filter += fmt.Sprintf(" AND is_hot = %d", isNew)
		}
	}

	if isFav == 1 {
		if len(filter) == 0 {
			filter += fmt.Sprintf(" is_fav = %d", isNew)
		} else {
			filter += fmt.Sprintf(" AND is_fav = %d", isNew)
		}
	}

	if online == 1 {
		if len(filter) == 0 {
			filter = fmt.Sprintf("online = %d", online)
		} else {
			filter += fmt.Sprintf(" AND online = %d", online)
		}
	}
	if gameId != "" {
		if len(filter) == 0 {
			filter = fmt.Sprintf("game_id = %d", gameId)
		} else {
			filter += fmt.Sprintf(" AND game_id = %d", gameId)
		}
	}
	if word != "" {
		decodedValue, err := url.QueryUnescape(word)
		if err != nil {
			helper.RetData(ctx, false, "参数错误")
			return
		}
		word = decodedValue
	}

	data, err := model.GameFullTextMeili(page, pageSize, filter, word, orderBy, OderType)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, data)

}

func (that *GameController) UpdateBatchHot(ctx *fasthttp.RequestCtx) {

	val := ctx.QueryArgs().GetUintOrZero("val")
	id := string(ctx.QueryArgs().Peek("id"))
	if !helper.CtypeCommaDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	ids := strings.SplitN(id, ",", 100)
	err := model.GameBatchUpdate("is_hot", val, ids)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *GameController) UpdateBatchRec(ctx *fasthttp.RequestCtx) {

	val := ctx.QueryArgs().GetUintOrZero("val")
	id := string(ctx.QueryArgs().Peek("id"))
	if !helper.CtypeCommaDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	ids := strings.SplitN(id, ",", 100)
	err := model.GameBatchUpdate("is_new", val, ids)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *GameController) UpdateBatchFav(ctx *fasthttp.RequestCtx) {
	field := string(ctx.QueryArgs().Peek("field"))
	val := ctx.QueryArgs().GetUintOrZero("val")
	id := string(ctx.QueryArgs().Peek("id"))
	if !helper.CtypeCommaDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	var fileds = []string{"online", "is_hot", "is_new", "is_fav", "hot_sort", "new_sort", "fav_sort", "maintained", "to_fake"}
	is_normal := false
	for _, item := range fileds {
		if item == field {
			is_normal = true
		}
	}
	if !is_normal {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	ids := strings.SplitN(id, ",", 100)
	err := model.GameBatchUpdate(field, val, ids)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// 维护游戏的上线下线
func (that *GameController) UpdateState(ctx *fasthttp.RequestCtx) {

	id := string(ctx.QueryArgs().Peek("id"))
	if !helper.CtypeDigit(id) {
		helper.RetData(ctx, false, helper.IDErr)
		return
	}

	online := ctx.QueryArgs().GetUintOrZero("online")

	/*
		// 上线的热门游戏不能超过8个
		if online == 1 {
			total, err := model.CountHotGame(id)
			if err != nil {
				helper.RetData(ctx, false, err.Error())
				return
			}

			if total >= 8 {
				helper.RetData(ctx, false, helper.HotGameNumLimit)
				return
			}
		}
	*/
	err := model.GameListUpdateState(id, online)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// 游戏编辑
func (that *GameController) Update(ctx *fasthttp.RequestCtx) {

	param := model.Game_item{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.Img == "" || !strings.Contains(param.Img, ".") {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	record := g.Record{
		"maintained":  param.Maintained,
		"online":      param.Online,
		"is_new":      param.IsNew,
		"is_hot":      param.IsHot,
		"is_fav":      param.IsFav,
		"en_name":     param.EnName,
		"name":        param.Name,
		"img":         param.Img,
		"br_alias":    param.BrAlias,
		"client_type": param.ClientType,
		"sorting":     param.Sorting,
		"hot_sort":    param.HotSort,
		"new_sort":    param.NewSort,
		"fav_sort":    param.FavSort,
		"to_fake":     param.ToFake,
	}

	if param.EnName != "" {
		decodedValue, err := url.QueryUnescape(param.EnName)
		if err != nil {
			helper.RetData(ctx, false, "参数错误")
			return
		}
		record["en_name"] = decodedValue
	}
	if param.BrAlias != "" {
		decodedValue, err := url.QueryUnescape(param.BrAlias)
		if err != nil {
			helper.RetData(ctx, false, "参数错误")
			return
		}
		record["br_alias"] = decodedValue
	}
	if param.Name != "" {
		decodedValue, err := url.QueryUnescape(param.Name)
		if err != nil {
			helper.RetData(ctx, false, "参数错误")
			return
		}
		record["name"] = decodedValue
	}

	err = model.GameListUpdate(param.ID, record)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *GameController) Upload(ctx *fasthttp.RequestCtx) {

	filename, err := model.GameImgUpload(ctx)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, filename)
}

type GameListRequest struct {
	Page     int    `json:"page" cbor:"page"`
	PageSize int    `json:"pageSize" cbor:"page_size"`
	OderBY   string `json:"order_by"`
	OderType string `json:"order_type"`
}

// 游戏列表
func (that *GameController) List(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	//name := string(ctx.QueryArgs().Peek("name"))
	brName := string(ctx.QueryArgs().Peek("word"))
	//enName := string(ctx.QueryArgs().Peek("enName"))
	platformId := string(ctx.QueryArgs().Peek("platform_id"))
	gameType := ctx.QueryArgs().GetUintOrZero("game_type")
	gameId := string(ctx.QueryArgs().Peek("game_id"))
	online := string(ctx.QueryArgs().Peek("online"))
	maintained := string(ctx.QueryArgs().Peek("maintained"))
	isHot := ctx.QueryArgs().GetUintOrZero("is_hot") //热门
	isNew := ctx.QueryArgs().GetUintOrZero("is_new") //推荐 1 开启  2 关闭
	isFav := ctx.QueryArgs().GetUintOrZero("is_fav") //最新
	orderBy := string(ctx.QueryArgs().Peek("order_by"))
	OderType := string(ctx.QueryArgs().Peek("order_type"))
	router := string(ctx.QueryArgs().Peek("router"))
	toFake := string(ctx.QueryArgs().Peek("to_fake"))
	ex := g.Ex{}

	if isHot == 1 {
		ex["is_hot"] = isHot
	}
	if isNew == 1 {
		ex["is_new"] = isNew
	}
	if isFav == 1 {
		ex["is_fav"] = isFav
	}

	if online != "" {
		ex["online"] = online
	}
	if maintained != "" {
		ex["a.maintained"] = maintained
	}
	if gameId != "" {
		ex["game_id"] = gameId
	}
	if toFake != "" {
		ex["to_fake"] = toFake
	}
	if brName != "" {
		decodedValue, err := url.QueryUnescape(brName)
		if err != nil {
			helper.RetData(ctx, false, "参数错误")
			return
		}
		Condition := fmt.Sprintf("%%%s%%", decodedValue)
		ex["a.br_alias"] = g.Op{"LIKE": Condition}
	}
	if platformId != "" {
		ex["pid"] = platformId
	}
	if gameType != 0 {
		ex["a.game_type"] = gameType
	}

	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 15
	}
	data, err := model.GameList(ex, uint(page), uint(pageSize), orderBy, OderType, platformId, router)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}
